<?php
require_once "services/securityServices.php";
require_once "services/budgetServices.php";
require_once "services/BusinessLogic.php";

require_once 'viewbean/AutoReconcile.php';
require_once 'viewbean/BudgetItem.php';
require_once 'viewbean/Transaction.php';
require_once 'viewbean/BudgetStatViewBean.php';
require_once 'viewbean/KeyValueBean.php';

require_once "errorCodes.php";
require_once "dto/Action.php";
require_once "classes.php";


class BusinessLogic{
	
	public function saveBudgetItemAccountAssociation($parameters){
		$accountId = $parameters["accountId"];
		$budgetitemid = $parameters["budgetitemid"];
	
		$budgetServices = new BudgetService;
		try {
			$budgetServices->saveBudgetItemAccountAssociation($budgetitemid, $accountId);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('007');
		}
		$responder = new Responder;
		return $responder->constructResponse(null);
	}
	
	public function getBudgetItemsForUser($parameters){
		$userid = $_SESSION["userid"];
	
		$budgetServices = new BudgetService;
		try {
			$itemslist = $budgetServices->getBudgetItemsForUser($userid);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('007');
		}
		$responder = new Responder;
		return $responder->constructResponse($itemslist);
	}
	
	public function deleteBudgetItemAccountAssociation($parameters){
		$associationId = $parameters["associationId"];
	
		$budgetServices = new BudgetService;
		try {
			 $budgetServices->deleteBudgetItemAccountAssociation($associationId);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('007');
		}
		$responder = new Responder;
		return $responder->constructResponse(null);
	}
	
	public function getBudgetItemAccountAssociation($parameters){
		$userid = $_SESSION["userid"];
	
		$budgetServices = new BudgetService;
		try {
			$itemslist = $budgetServices->getBudgetItemAccountAssociation($userid);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('007');
		}
		$responder = new Responder;
		return $responder->constructResponse($itemslist);
	}
	
	public function retrieveEquityDataForUser($parameters){
		$userid = $parameters["userid"];

		$budgetServices = new BudgetService;
		$service = new CommonServices;
		try {
			$itemslist = $budgetServices->retrieveEquityDataForUser($userid);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('007');
		}
		$responder = new Responder;
		return $responder->constructResponse($itemslist);
	}
	
	public function getPastDataForBudgetItem($parameters){
		$budgetItemId = $parameters["budgetItemId"];
		$numOfMonths = 24;
		$numOfMonths = $numOfMonths * -1;
		$userid = $parameters["userid"];

		$budgetServices = new BudgetService;
		$service = new CommonServices;
		try {
			$itemslist = array();

			for ($month=0; $month > $numOfMonths; $month--){
				$budgetid = $budgetServices->getBudgetByMonth($userid, $service->getMonthName($month, $userid, "long"));
				$budgetAmount =  $budgetServices->getActualAmountForBudgetItemInBudget($budgetid, $budgetItemId);

				error_log("BUDGET AMOUNT: ".$budgetAmount. " AND MONTH IS: ".$service->getMonthName($month, $userid, "long"));
				$monthStartDate = $service->getStartDateOfBudget($month, $userid);
				$monthEndDate = $service->getEndDateOfBudget($month, $userid);
				$actualAmount = $budgetServices->getSumOfBudgetItemTransactions($budgetItemId, $monthStartDate, $monthEndDate) * -1;
				$monthName = $service->getMonthName($month, $userid, "full");
				$statViewBean = new BudgetStatViewBean($monthName, $budgetAmount, $actualAmount);

				array_push($itemslist, $statViewBean);
			}


		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('007');
		}
		$responder = new Responder;
		return $responder->constructResponse($itemslist);
	}

	public function updateBudgetItem($parameters){
		$description = $parameters["description"];
		$budgetItemId = $parameters["budgetItemId"];
		$budgetService = new BudgetService;
		try {
			$budgetService->updateBudgetItem($budgetItemId, $description);

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('007');
		}
		$responder = new Responder;
		return $responder->constructResponse(null);
	}

	public function getAllBudgetItemsForCurrentBudget($parameters){
		$userid = $parameters["userid"];
		$service = new CommonServices;
		$budgetId = $service->getCurrentBudgetId($userid);

		$budgetService = new BudgetService;
		try {

			$itemslist = array();
			for ($counter = 1; $counter <= 5; $counter++) {
				$budgetItems = 	$budgetService->getBudgetItemsForCategory($budgetId, $counter);
				foreach($budgetItems as $budgetItem){
					array_push($itemslist, $budgetItem);
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('001');
		}

		$responder = new Responder;
		return $responder->constructResponse($itemslist);
	}

	public function getAccountsForUser($parameters){
		$userid = $parameters["userid"];
		if ($userid == "myself"){
			$userid = $_SESSION["userid"];
		}
		
		$budgetService = new BudgetService;
		try {

			$accounts = $budgetService->getAccountsForUser($userid);

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('001');
		}

		$responder = new Responder;
		return $responder->constructResponse($accounts);
	}

	public function loginUser($parameters){

		$username = $parameters["username"];
		$password = $parameters["password"];
		$securityServices = new SecurityService;

		$securityServices->loginUser($username, $password);

		$responder = new Responder;
		return $responder->constructResponse(null);
	}

	public function getBudgetItemTransactions($parameters){
		$fromDate = $parameters["fromDate"];
		$toDate = $parameters["toDate"];
		$userid = $parameters["userid"];
		$budgetId = $parameters["budgetId"];
		$budgetItemId =  $parameters["budgetItemId"];

		$service = new CommonServices;

		if ($budgetId == "current"){
			$budgetId = $service->getCurrentBudgetId($userid);
		}

		if ($fromDate == "startOfBudget"){
			$fromDate = $service->getStartDateForBudget($budgetId);
		}


		if ($toDate == "endOfBudget"){
			$toDate = $service->getEndDateForBudget($budgetId);
		}


		try {
			$budgetServices = new BudgetService;
			$transactions = $budgetServices->getBudgetItemTransactions($budgetItemId, $fromDate, $toDate);

		} catch (Exception $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('017');
		}

		$responder = new Responder;
		return $responder->constructResponse($transactions);
	}

	public function insertBudgetItemIntoBudget($parameters){
		try {
			$budgetServices = new BudgetService;
			$budgetItemId = $budgetServices->insertBudgetItemIntoBudget($parameters["budgetItemId"], $parameters["budgetId"], 0 , 0);

		} catch (Exception $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('017');
		}
	}

	public function createBudgetItem($parameters){
		$userid = $parameters["userid"];
		try {
			$budgetServices = new BudgetService;
			$budgetItemId = $budgetServices->createBudgetItem($userid, $parameters["categoryId"], $parameters["description"]);

			$responseArray = array("budgetItemId" => $budgetItemId);

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('018');
		}

		$responder = new Responder;
		return $responder->constructResponseForKeyValue($responseArray);
	}

	public function getNewBudgetId($parameters){
		$userid = $parameters["userid"];
		try {
			$budgetServices = new BudgetService;
			$budgetId = $budgetServices->getNewBudgetId($parameters["userid"]);

			$responseArray = array("budgetId" => $budgetId);

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('018');
		}

		$responder = new Responder;
		return $responder->constructResponseForKeyValue($responseArray);
	}

	public function getUnreconciledTransactionsForBudget($parameters){
		$service = new CommonServices;
		$userid = $parameters["userid"];
		$budgetId = $parameters["budgetId"];
		if ($budgetId == "current"){
			$budgetId = $service->getCurrentBudgetId($userid);
		}

		try {
			$endDate = date("Y-m-d");

			$startDate = $service->getStartDateForBudget($budgetId);
			error_log("START DATE: " .$startDate);

			$budgetServices = new BudgetService;
			$unreconciledTransactions = $budgetServices->getUnreconciledTransactions($startDate, $endDate, $userid);

			$responder = new Responder;
			return $responder->constructResponse($unreconciledTransactions);

		} catch (Exception $e){
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
		}

	}

	public function getStartOfMonthDate($parameters){
		try {
			$budgetServices = new BudgetService;
			$budgetStartDate = $budgetServices->getStartOfMonthDate($parameters["userid"]);

			$responseArray = array("firstdayofmonth" => $budgetStartDate);

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('018');
		}

		$responder = new Responder;
		return $responder->constructResponseForKeyValue($responseArray);
	}

	public function createCurrentBudget($parameters){
		$parameters["userid"] = $_SESSION["userid"];
		$budgetServices = new BudgetService;
		$budgetStartDate = $budgetServices->getStartOfMonthDate($parameters["userid"]);

		try {

			if ($budgetStartDate > date("j")){
				error_log("DATE HAS NOT PASSED: ".date("F Y"));
				$parameters["budgetDate"] = date("F Y");
			} else {
				error_log("DATE HAS PASSED: ".date("F Y", strtotime("+1 months")));
				$parameters["budgetDate"] = date("F Y", strtotime("+1 months"));
			}

			$budgetServices->createBudget($parameters);
			$budgetId = $budgetServices->getBudgetIdForLastBudgetForUser($parameters["userid"]);

			//Do autoreconcile
			$accountId = $budgetServices->getFirstTransactionalAccountId($parameters["userid"]);
			$transactions = $budgetServices->getAllTransactionsForAccount($accountId);

			$autoreconciles = $budgetServices->getMasterReconcileData($parameters);

			$createdBudgetItems = array();
			foreach ($transactions as  $transaction){
				foreach ($autoreconciles as $autoreconcile){
					if (strlen(strstr($transaction->bankRef, $autoreconcile->key))>0) {


						error_log("FOUND!!! ---->". $autoreconcile->key. " ---> ".$autoreconcile->group);

						$autoreconcileStatus = "false";
						if (!in_array($autoreconcile->group, $createdBudgetItems)){
							//Create a budget Item
							$budgetItemId = $budgetServices->createBudgetItem($parameters["userid"], $autoreconcile->budgetitemid, $autoreconcile->group);

							//Insert this budget item in the current budget
							$budgetServices->insertBudgetItemIntoBudget($budgetItemId, $budgetId, 0, 0);
							array_push($createdBudgetItems, $autoreconcile->group);

							$autoreconcileStatus = "true";
						}

						$parameters1 = array();

						//Reconcile the transaction

						$parameters1["transId"] = $transaction->id;
						$parameters1["transDate"] = $transaction->date;
						$parameters1["transDescription"] = $autoreconcile->value;
						$parameters1["autoReconcile"] = $autoreconcileStatus;
						$parameters1["transDescriptor"] = $autoreconcile->key;
						$parameters1["categoryId"] = $transaction->categoryId;
						$parameters1["reconciled"] = "true";
						$parameters1["transAmount"] = $transaction->amount;
						$parameters1["budgetItemId"] = $budgetItemId;
						$parameters1["accId"] = $accountId;
						$parameters1["userid"] = $parameters["userid"];
						$budgetServices->saveTransaction($parameters1);

					}
				}
			}

		} catch (Exception $e){
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('017');
		}

		$responder = new Responder;
		return $responder->constructResponse(null);
	}

}
?>